// Handling of certificates and keypairs for SSLStreamAdapter's peer mode.

#ifndef BASE_SSLIDENTITY_H__
#define BASE_SSLIDENTITY_H__

#include <string>
#include "messagedigest.h"

namespace base {

	// Abstract interface overridden by SSL library specific
	// implementations.

	// A somewhat opaque type used to encapsulate a certificate.
	// Wraps the SSL library's notion of a certificate, with reference counting.
	// The SSLCertificate object is pretty much immutable once created.
	// (The OpenSSL implementation only does reference counting and
	// possibly caching of intermediate results.)
	class SSLCertificate {
	public:
		// Parses and build a certificate from a PEM encoded string.
		// Returns NULL on failure.
		// The length of the string representation of the certificate is
		// stored in *pem_length if it is non-NULL, and only if
		// parsing was successful.
		// Caller is responsible for freeing the returned object.
		static SSLCertificate* FromPEMString(const std::string& pem_string,
			int* pem_length);
		virtual ~SSLCertificate() {}

		// Returns a new SSLCertificate object instance wrapping the same
		// underlying certificate.
		// Caller is responsible for freeing the returned object.
		virtual SSLCertificate* GetReference() const = 0;

		// Returns a PEM encoded string representation of the certificate.
		virtual std::string ToPEMString() const = 0;

		// Compute the digest of the certificate given algorithm
		virtual bool ComputeDigest(const std::string &algorithm,
			unsigned char *digest, std::size_t size,
			std::size_t *length) const = 0;
	};

	// Our identity in an SSL negotiation: a keypair and certificate (both
	// with the same public key).
	// This too is pretty much immutable once created.
	class SSLIdentity {
	public:
		// Generates an identity (keypair and self-signed certificate). If
		// common_name is non-empty, it will be used for the certificate's
		// subject and issuer name, otherwise a random string will be used.
		// Returns NULL on failure.
		// Caller is responsible for freeing the returned object.
		static SSLIdentity* Generate(const std::string& common_name);

		virtual ~SSLIdentity() {}

		// Returns a new SSLIdentity object instance wrapping the same
		// identity information.
		// Caller is responsible for freeing the returned object.
		virtual SSLIdentity* GetReference() const = 0;

		// Returns a temporary reference to the certificate.
		virtual const SSLCertificate& certificate() const = 0;
	};

}  // namespace base

#endif  // BASE_SSLIDENTITY_H__
